# Simple aqw python
# V0.0.1

from it.gotoandplay.smartfoxserver.exceptions import LoginException

def init():

    _server.trace("Initing dbExtension, Zone Extension")
    global db
    global zone

    db = _server.getDatabaseManager()
    zone = _server.getCurrentZone()


def destroy():
	_server.trace("Python extension dying")


def handleInternalEvent(evt):
    evt_Name = evt.getEventName()
    _server.trace("Received internal event: " + evt_Name)

    if evt_Name == "serverReady":
        _server.trace("Server is ready!")

    elif evt_Name == "loginRequest":

        nick = evt.getParam("nick").split("~")[1]
        chan = evt.getObject("chan")
        word = evt.getParam("pass")

       	sql = "SELECT id FROM users WHERE Username='" + nick + "' AND Password='" + word + "'"
        queryRes = db.executeQuery(sql)

        if (queryRes != None) and (queryRes.size() > 0):
            for row in queryRes:

                item = {}
                item["id"] = row.getItem("id")

                _server.trace("UserID:" + item["id"] + "\n" + " Username:" + nick + "\n Password:" + word)
                try:
                    _server.loginUser(nick, word, chan)

                    login_data = []
                    login_data.append("loginResponse")
                    login_data.append("true")
                    login_data.append(item["id"])
                    login_data.append(nick)
                    login_data.append("SmartFoxServer Python Test!")
                    login_data.append("2014-12-17T23:34:30")
                    login_data.append("sNews=news/News-12Dec14.swf,sMap=news/Map-25June14r1.swf,sBook=news/Book-18nov13.swf,sFBC=FBC-2011-03-08.swf,sAssets=Assets_20140627.swf,sWTSandbox=false,gMenu=gameMenu3-12Dec14r1.swf")

                    _server.sendResponse(login_data, -1, None, chan, _server.PROTOCOL_STR)

                except LoginException, message:
                    _server.trace("SFS ERROR:\n" + message)

    elif evt_Name == "userJoin":
        user = evt.getObject("user")
        room = evt.getObject("room")


def handleRequest(cmd, params, user, fromRoom, protocol):
    aparams = ""
    for aparams in params:
        pass
    _server.trace("CMD:" + cmd + "\n" + "Params:" + aparams)

    if cmd == "firstJoin":
        joinRoom(user, "battleon")

def handleGetData(params, user, roomId):
    pass


def joinRoom(user, roomName):
    roomName = roomName.lower()

    room = zone.getRoomByName(roomName)
    if room is not None:
        _server.joinRoom(user, user.getRoom(), room.getId(), True, "")
        _server.trace("User Joined:" + roomName)
    else:
        newRoom = createNewRoom(roomName)

        if newRoom is not None:
            _server.trace("User Joined:" + newRoom)
            _server.joinRoom(user, user.getRoom(), room.getId(), True, "")

def createNewRoom(roomname):
    try:
        alreadyExist = zone.getRoomByName(roomname)

        if alreadyExist == None:
            rmname = roomname

            rObj = {}
            rObj["name"] = roomname
            rObj["pwd"] = ""
            rObj["maxU"] = 10000
            rObj["maxS"] = 0
            rObj["isGame"] = "false"
            rObj["uCount"] = "false"
            _server.trace(rObj)
            _server.createRoom(rObj, None)

    except LoginException, message:
        _server.trace("SFS ERROR:\n" + message)